import Vue from 'vue';
import VueRouter from 'vue-router';

// 注册组件 <router-view> <router-link>
Vue.use(VueRouter);

// import Home from '../views/Home.vue'
// import Shop from '../views/Shop.vue'
// import Order from '../views/Order.vue'
// import Cart from '../views/Cart.vue'
// import NotFound from '../views/NotFound.vue'
// import TopNav from '../views/TopNav.vue'
// import TopBar from '../views/TopBar.vue'
import Layout from '../views/Layout.vue'

const router = new VueRouter({
  mode: 'history',
  // 路由表
  // http://localhost:8081#/
  routes: [
    {
      path: '/',
      name: 'sy',
      redirect: { name: 'home' },
      meta: {
        hidden: true,
      }
    },
    {
      path: '/gc',
      component: Layout,
      name: 'gc',
      redirect: { name: 'home' },
      meta: {
        label: '广场',
        icon: 'fa-solid fa-cart-shopping',
      },
      children: [
        {
          path: 'home',
          name: 'home',
          component: () => import(/* webpackChunkName: "g1" */'../views/Home.vue'),
          meta: {
            label: '首页',
            icon: 'fa-solid fa-house'
          }
        },
        {
          path: 'order',
          name: 'order',
          component: () => import(/* webpackChunkName: "g1" */'../views/Order.vue'),
          meta: {
            label: '订单',
            icon: 'fa-solid fa-arrow-down-short-wide',
            needLogin: true,
            auth: ['admin'],
          }
        },
      ]
    },
    {
      path: '/center',
      component: Layout,
      name: 'center',
      redirect: { name: 'cart' },
      meta: {
        label: '个人中心',
        icon: 'fa-solid fa-cart-shopping',
      },
      children: [
        {
          path: '/cart',
          name: 'cart',
          component: () => import(/* webpackChunkName: "g2" */'../views/Cart.vue'),
          meta: {
            label: '购物车',
            icon: 'fa-solid fa-cart-shopping',
            needLogin: true,
            auth: ['admin', 'user'],
          }
        },
        {
          path: '/shop',
          name: 'shop',
          component: () => import(/* webpackChunkName: "g2" */'../views/Shop.vue'),
          meta: {
            label: '商城',
            icon: 'fa-solid fa-shop',
            auth: ['user']
          }
        },
      ]
    },

    {
      path: '/topbar',
      name: 'topbar',
      component: () => import(/* webpackChunkName: "g3" */'../views/TopBar.vue'),
      meta: {
        hidden: true,
      }
    },
  ]
});


localStorage.token = 'hhh';
localStorage.role = 'admin';
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.needLogin === true) {
    if (localStorage.token === undefined) {
      //没有登录
      next(false);
    } else {
      //已经登录，判断权限
      if (to.meta.auth !== undefined && to.meta.auth.includes(localStorage.role) === false) {
        next(false)
      } else {
        next();
      }
    }
  } else {
    // 不需要登录放行
    next();
  }
})


export default router;